﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.Threading;
using SilverlightSdms.AdminService;

namespace SilverlightSdms.Views
{

    public partial class Login : Page
    {
        

        public Login()
        {
            InitializeComponent();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            busyIndicatorLogin.IsBusy = true;
            ValidateUser();
        }

        private void ValidateUser()
        {
            var client = new UsersServiceClient();
            client.GetUsersWithRolesCompleted += (s, ea) =>
            {
                LightUser user;
                try
                {
                    user = ea.Result.First(u => u.UserName == txtboxUserName.Text && u.Password == txtBoxPassword.Text);
                }
                catch//First throw exception if no user found
                {
                    user = null;
                }

                if (user != null)
                {
                    this.NavigationService.Navigate(new Uri("/About", UriKind.Relative));
                    TxtBlockErrorMsg.Visibility = System.Windows.Visibility.Collapsed;
                    ((App)Application.Current).AddRoleType(user.Roles.ToList());
                    ((App)Application.Current).UserId = user.Id;
                }
                else
                {
                    TxtBlockErrorMsg.Visibility = System.Windows.Visibility.Visible;
                }
                
                busyIndicatorLogin.IsBusy = false;
            };
            client.GetUsersWithRolesAsync();
        }

        private void btnLoginWithoutAuthentication_Click(object sender, RoutedEventArgs e)
        {
            ((App)Application.Current).AddRoleType(eRoleType.Administrator.ToString());
            this.NavigationService.Navigate(new Uri("/About", UriKind.Relative));
            TxtBlockErrorMsg.Visibility = System.Windows.Visibility.Collapsed;
            ((App)Application.Current).UserId = 1;
        }




    }
}
